from deps.voidsdk.pytoolset.datetime import now
from deps.voidsdk.django.responses import api_error_response

from .models import ApiAccessToken


def api_auth_required(func):
    def wrapped(request, *args, **kwargs):
        access_token = request.META.get("HTTP_ACCESS_TOKEN", None)
        if not access_token:
            return api_error_response(u"缺少access token")
        token_records = ApiAccessToken.objects.filter(access_token=access_token,
                expire_timestamp__gt=now())
        if token_records.exists():
            request.user = token_records[0].user
            return func(request, *args, **kwargs)
        else:
            return api_error_response(u"access_token无效", status="access_token_expired")
    return wrapped
